<?php
declare(strict_types=1);


namespace App\Fastapp\Mapper;

use App\Fastapp\Model\FastappAppSetting;
use App\Fastapp\Model\FastappChannel;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;
use Mine\Helper\Str;

/**
 * 平台渠道Mapper类
 */
class FastappChannelMapper extends AbstractMapper
{
    /**
     * @var FastappChannel
     */
    public $model;

    public function assignModel()
    {
        $this->model = FastappChannel::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        if (isset($params['key']) && filled($params['key'])) {
            $query->where('key', '=', $params['key']);
        }
        if (isset($params['user_id']) && filled($params['user_id'])) {
            $query->where('user_id', '=', $params['user_id']);
        }
        if (isset($params['admin_id']) && filled($params['admin_id'])) {
            $query->where('admin_id', '=', $params['admin_id']);
        }

        return $query;
    }

    public function save(array $data): mixed
    {
        $data['key'] = Str::random(8, 3);
        $s = parent::save($data);
        redis()->hMSet('channel', $this->model::query()->pluck('id', 'key')->toArray());
        return $s;
    }

    public function handlePageItems(array $items, array $params): array
    {
        $app_url = FastappAppSetting::query()->where(['key' => 'app_domain'])->pluck('val', 'account_type')->toArray();
        $app_name = FastappAppSetting::query()->where(['key' => 'app_name'])->pluck('val', 'account_type')->toArray();
        foreach ($items as $item) {
            $urls = [];
            foreach ($app_url as $k => $v) {
                $host = parse_url($v)['host'];
                $urls[] = ['name' => $app_name[$k], 'url' => str_replace($host, $item->key . '.' . $host, $v)];
            }
            $item->invite_url = $urls;
        }
        return $items;
    }
}